//
//  myFocusViewController.m
//  唧歪
//
//  Created by ZC on 15/9/2.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "myFocusViewController.h"
#import "AppDelegate.h"
#import "MyFocusCell.h"
#import "FocusMe.h"
#import "FocusPostViewController.h"
#import "addressBookModel.h"
#define myFocusURL @"https://app.jiwaipro.com:8888/index.php/JiWai/myfocuslist"


@interface myFocusViewController (){
    AppDelegate *app;
    NSMutableArray *array;
    NSMutableArray *myFocusArray;
    NSMutableArray *id_array;
    MyFocusCell *cell;
    NSMutableArray *focusMe_shieldArray;
    NSMutableArray *addressBookTemp;
}

@end

@implementation myFocusViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    array = [NSMutableArray array];
    myFocusArray = [NSMutableArray array];
    id_array = [NSMutableArray array];
    focusMe_shieldArray = [NSMutableArray array];
    
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
    }else{
        NSString *string = [NSString stringWithFormat:@"user_id=%@",app.user_id];
        [self FocusMePath:myFocusURL Str:string];
        app.Existence = @"0";
    }
    [self readAddressBook];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)FocusMePath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        array =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:array waitUntilDone:YES];
    }];
}
- (void)refreshData:(NSMutableArray *)sender{
    for(int i = 0;i<sender.count-1;i++){
        FocusMe *fm = [[FocusMe alloc] init];
        fm.FocusMe_image=[NSString stringWithFormat:@"%@",sender[i][@"user_headPortrait"]];
        fm.FocusMe_phone=[NSString stringWithFormat:@"%@",sender[i][@"user_phone"]];
        fm.FocusMe_user_id=[NSString stringWithFormat:@"%@",sender[i][@"user_id"]];
        fm.focusMe_shield=[NSString stringWithFormat:@"%@",sender[sender.count-1][i]];
        [myFocusArray addObject:fm];
    }
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return myFocusArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UINib *nib=[UINib nibWithNibName:@"MyFocusCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"MyFocusCell"];
    
    static NSString *cellIdentifier=@"MyFocusCell";
    cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    FocusMe *fm = myFocusArray[indexPath.row];
    cell.image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",fm.FocusMe_image]]]];
    for (int i=0; i<addressBookTemp.count; i++) {
        addressBookModel *book = addressBookTemp[i];
        if ([fm.FocusMe_phone isEqualToString:book.tel]) {
            cell.phone.text = book.name;
        }else{
            //把手机号码的中间3位换成 *
            NSString *star=[fm.FocusMe_phone stringByReplacingCharactersInRange:NSMakeRange(4, 3) withString:@"***"];
            cell.phone.text = [NSString stringWithFormat:@"%@",star];
        }
    }
    
    cell.user_id = [NSString stringWithFormat:@"%@",fm.FocusMe_user_id];
    cell.focus_shield = [NSString stringWithFormat:@"%@",fm.focusMe_shield];
    [focusMe_shieldArray addObject:cell.focus_shield];
    
    [id_array addObject:cell.user_id];
    
    [cell.focus setOn:YES animated:YES];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([focusMe_shieldArray[indexPath.row] isEqualToString:@"1"]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"爱心提示" message:@"您已被该用户屏蔽，暂时不能查看他的帖子!!!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
    app.myFocus_id = id_array[indexPath.row];
    FocusPostViewController *focusePost = [self.storyboard instantiateViewControllerWithIdentifier:@"focusPostVC"];
    [self.navigationController pushViewController:focusePost animated:YES];
    }
}
#pragma mark - 调取通讯录
-(void)readAddressBook{
    //数组初始化
    addressBookTemp=[NSMutableArray array];
    //新建一个通讯类
    ABAddressBookRef addressBooks = nil;
    
    //如果系统是ios6之后
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
        
    {
        addressBooks =  ABAddressBookCreateWithOptions(NULL, NULL);
        
        //获取通讯录权限
        
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        
        ABAddressBookRequestAccessWithCompletion(addressBooks, ^(bool granted, CFErrorRef error){dispatch_semaphore_signal(sema);});
        
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        
        
    }
    
    else
        
    {
        addressBooks = ABAddressBookCreateWithOptions(NULL, NULL);
        
    }
    
    //获取通讯录中的所有人
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);
    
    //通讯录中人数
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);
    
    //循环，获取每个人的个人信息
    for (NSInteger i = 0; i < nPeople; i++)
    {
        //新建一个addressBook model类
        addressBookModel *addressBook = [[addressBookModel alloc] init];
        //获取个人
        ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
        //获取个人名字
        CFTypeRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
        CFTypeRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
        CFStringRef abFullName = ABRecordCopyCompositeName(person);
        NSString *nameString = (__bridge NSString *)abName;
        NSString *lastNameString = (__bridge NSString *)abLastName;
        
        if ((__bridge id)abFullName != nil) {
            nameString = (__bridge NSString *)abFullName;
        } else {
            if ((__bridge id)abLastName != nil)
            {
                nameString = [NSString stringWithFormat:@"%@ %@", nameString, lastNameString];
            }
        }
        addressBook.name = nameString;
        addressBook.recordID = (int)ABRecordGetRecordID(person);;
        
        ABPropertyID multiProperties[] = {
            kABPersonPhoneProperty,
            kABPersonEmailProperty
        };
        NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);
        for (NSInteger j = 0; j < multiPropertiesTotal; j++) {
            ABPropertyID property = multiProperties[j];
            ABMultiValueRef valuesRef = ABRecordCopyValue(person, property);
            NSInteger valuesCount = 0;
            if (valuesRef != nil) valuesCount = ABMultiValueGetCount(valuesRef);
            
            if (valuesCount == 0) {
                CFRelease(valuesRef);
                continue;
            }
            //获取电话号码和email
            for (NSInteger k = 0; k < valuesCount; k++) {
                CFTypeRef value = ABMultiValueCopyValueAtIndex(valuesRef, k);
                switch (j) {
                    case 0: {// Phone number
                        addressBook.tel = (__bridge NSString*)value;
                        break;
                    }
                    case 1: {// Email
                        addressBook.email = (__bridge NSString*)value;
                        break;
                    }
                }
                CFRelease(value);
            }
            CFRelease(valuesRef);
        }
        //将个人信息添加到数组中，循环完成后addressBookTemp中包含所有联系人的信息
        [addressBookTemp addObject:addressBook];
    }
}

@end
